import ReList from "./ReList";
import React, { Component } from 'react'
import { listArticleInfoReq, queryArticleAmount } from "../../requests/article";
import { message } from "antd"
import ArticleType from '../../types/ArticleType'
import ArticleInfo from "../../types/ArticleInfo";
import { getRes } from "../../configFile";

//state接口
interface IState {
    listArticleInfo: Array<Pick<ArticleInfo, "articleID" | "articleType" | "title" | "authorID" | "creationTimestamp" | "lastModifiedTimestamp">>
}

//props接口
interface IProps {
    recommendType: ArticleType,
    title: React.ReactNode
}

export default class RecommendedReq extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            listArticleInfo: [],
        }
    }

    getData = async () => {
        try {
            const amountRes = getRes(await queryArticleAmount(this.props.recommendType));
            if (amountRes.isSuccessful) {
                const res = getRes(await listArticleInfoReq(this.props.recommendType,
                    Math.floor(Math.random() * amountRes.data / 5), 5))
                if (res.isSuccessful) {
                    this.setState({
                        listArticleInfo: res.data,
                    })
                } else {
                    message.error("获取失败" + res.message);
                }
            } else {
                message.error("获取失败" + amountRes.message);
                return;
            }

        }
        catch (error) {
            message.error(error.toString())
        }
    }

    refresh = async () => {
        await this.getData()
    }

    async componentDidMount() {
        await this.getData()
    }

    render() {
        return (
            <ReList key={Math.random()} refresh={this.refresh} title={this.props.title} articleList={this.state.listArticleInfo} />
        )
    }
}

